<template>
  <div class="meter-tree-container">
    <!-- 控制面板 -->
    <div class="control-panel">
      <el-space>
        <el-tooltip content="切换布局方向" placement="top">
          <div class="control-item">
            <el-switch v-model="horizontal" :active-value="true" :inactive-value="false" />
            <span class="control-label">
              <i class="fa" :class="horizontal ? 'fa-bars' : 'fa-sort'"></i>
              纵向展示
            </span>
          </div>
        </el-tooltip>

        <el-tooltip content="允许折叠节点" placement="top">
          <div class="control-item">
            <el-switch v-model="collapsable" />
            <span class="control-label">
              <i class="fa" :class="collapsable ? 'fa-minus-square-o' : 'fa-plus-square-o'"></i>
              节点折叠
            </span>
          </div>
        </el-tooltip>

        <div v-permission="'manage_device'">
          <el-tooltip content="启用节点拖拽" placement="top">
            <div class="control-item">
              <el-switch v-model="nodeDraggable" />
              <span class="control-label">
                <i class="fa" :class="nodeDraggable ? 'fa-arrows' : 'fa-lock'"></i>
                拖拽编辑
              </span>
            </div>
          </el-tooltip>
        </div>
        <el-tooltip content="刷新数据" placement="top">
          <div class="control-item">
            <el-button :loading="refreshing" link @click="handleRefresh">
              <template #icon>
                <i class="fa fa-refresh"></i>
              </template>
            </el-button>
          </div>
        </el-tooltip>
      </el-space>
    </div>

    <!-- 树形图主体 -->
    <div class="tree-container">
      <vue3-tree-org :key="meterListKey" :default-expand-level="2" :disabled="!isEdit" :horizontal="horizontal"
        :collapsable="collapsable" v-loading="loading" element-loading-text="加载中..." class="custom-tree-org"
        :data="data" :node-add="nodeAdd" :node-delete="nodeDelete" :node-edit="nodeEdit" :props="propsSetting"
        @on-node-drag-end="handleDragEnd" :only-one-node="false">
        <template v-slot="{ node }">
          <div class="tree-org-node__text" @click="handleNodeClick(node)">
            <div class="node-content">
              <div class="node-header" :class="{ 'is-center': node.$$data.isVirtualNode }">
                <i class="fa" :class="getNodeIconClass(node)"></i>
                <span class="node-title">{{ node.label }}</span>
              </div>
              <div class="node-info" v-if="!node.$$data.isVirtualNode">
                <el-tooltip :content="getAreaName(node)" placement="top" :disabled="!isAreaNameTruncated(node)">
                  <span class="node-area">
                    <i class="fa fa-map-marker"></i>
                    <span class="area-text">{{ getAreaName(node) }}</span>
                  </span>
                </el-tooltip>
                <span v-if="node.id !== 1" class="node-reading">
                  {{ latestReadings.get(node.id) ?? "加载中..." }}
                </span>
              </div>
            </div>
          </div>
        </template>
      </vue3-tree-org>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog :title="currentMeter ? '编辑表计' : '新增表计'" v-model="dialogVisible" destroy-on-close
      :close-on-click-modal="false">
      <MeterDialog @update:visible="dialogVisible = false" :pMeter="parent_meter" :id="currentMeter?.id"
        @success="handleDialogSuccess" />
    </el-dialog>

    <el-dialog :draggable="true" :append-to-body="true" style="height: 80vh; overflow: auto" title="表计详情"
      v-model="viewDialogVisible">
      <DeviceInfo></DeviceInfo>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { handleError } from "@/utils/handleError";
import { getLatestReadApi } from "@/api/meter";
import { useCompanyStore } from "@/stores/company";
import { useMeterStore } from "@/stores/meter";
import DeviceInfo from "@/views/DeviceCenter/DeviceInfo/components/DeviceInfo.vue";
import { useMeterStructure } from "./hooks/useMeterStructure";
import { usePermissionStore } from "@/stores/permission";
let permisstionStore = usePermissionStore()

// 接收props
const props = defineProps({
  meterList: {
    type: Array,
    default: () => []
  },
  treeData: {
    type: Array,
    default: () => []
  }
});

const isEdit = permisstionStore.hasPermission('manage_device')


// 状态与引用
const horizontal = ref(false);
const collapsable = ref(true);
const latestReadings = ref(new Map());
const refreshing = ref(false);

// Store实例
const meterStore = useMeterStore();
const companyStore = useCompanyStore();

let {
  dialogVisible,
  viewDialogVisible,
  currentMeter,
  parent_meter,
  loading,
  nodeDraggable,
  handleNodeClick,
  nodeAdd,
  nodeDelete,
  nodeEdit,
  handleDragEnd,
  handleDialogSuccess,
} = useMeterStructure(() => {
  emit('refresh');
});


const emit = defineEmits(['refresh']);

// 属性配置
const propsSetting = ref({
  label: "label",
  children: "children",
  id: "id",
  pid: "parent_id",
});
const data = computed(() => {
  // 递归函数：为节点及其子节点添加属性
  const addNoDraggingToNodes = (nodes) => {
    return nodes.map(node => {
      const newNode = {
        ...node,
      };

      // 如果有子节点，递归处理
      if (newNode.children && newNode.children.length > 0) {
        newNode.children = addNoDraggingToNodes(newNode.children);
      }

      return newNode;
    });
  };

  // 确定使用的数据来源
  const treeDataToUse = props.treeData.length > 0 ? props.treeData : meterStore.treeDataForChart;

  // 如果不是水表类型，则使用原来的树结构
  if (meterStore.currentSelectedType !== 1) {
    const processedChildren = addNoDraggingToNodes(treeDataToUse);
    return {
      id: 1,
      label: companyStore.currentCompany.name,
      children: processedChildren,
    };
  }

  // 为水表类型创建分组
  // 1. 创建参与和不参与不明水统计的分组节点
  const participatingGroup = {
    id: 'participating_group',
    label: '参与不明水统计一级表计',
    isVirtualNode: true,
    children: []
  };

  const nonParticipatingGroup = {
    id: 'non_participating_group',
    label: '不参与不明水统计的一级表计',
    isVirtualNode: true,
    children: []
  };

  let first_nodes = []
  treeDataToUse.forEach(node => {
    if (node.engine_id === 10) {
      node.isVirtualNode = true;
      first_nodes = node.meter_id?.split(',').map(id => +id) || [];
    }
  });

  treeDataToUse.forEach(node => {
    const nodeWithNoDragging = {
      ...node,
    };

    // 如果节点有子节点，递归处理子节点
    if (nodeWithNoDragging.children && nodeWithNoDragging.children.length > 0) {
      nodeWithNoDragging.children = addNoDraggingToNodes(nodeWithNoDragging.children);
    }

    if ((node.children && node.children.length > 0) || first_nodes.includes(node.id)) {
      participatingGroup.children.push(nodeWithNoDragging);
    } else {
      nonParticipatingGroup.children.push(nodeWithNoDragging);
    }
  });

  // 3. 构建最终的树结构
  const filteredChildren = [
    participatingGroup.children.length > 0 ? participatingGroup : null,
    nonParticipatingGroup.children.length > 0 ? nonParticipatingGroup : null
  ].filter(Boolean); // 过滤掉空组

  return {
    id: 1,
    label: companyStore.currentCompany.name,
    children: filteredChildren
  };
});


const meterListKey = computed(() => {
  return props.meterList.map(meter => meter.id).join(',')
})

// 获取最新读数
async function fetchLatestReading(meterId) {
  try {
    const res = await getLatestReadApi({ id: meterId });
    if (res.code === 200) {
      latestReadings.value.set(meterId, `${res.data.value}`);
    } else {
      latestReadings.value.set(meterId, "-- --");
    }
  } catch (err) {
    console.error("获取最新读数失败:", err);
    latestReadings.value.set(meterId, "-- --");
  }
}

// 刷新数据
async function handleRefresh() {
  if (refreshing.value) return;
  refreshing.value = true;
  try {
    await refreshLatestReadings();
    ElMessage.success("数据刷新成功");
  } catch (error) {
    handleError(error, "数据刷新失败", true);
  } finally {
    refreshing.value = false;
  }
}

// 刷新最新读数
async function refreshLatestReadings() {
  latestReadings.value.clear();
  const meterListToUse = props.meterList
  const promises = meterListToUse.map((meter) =>
    fetchLatestReading(meter.id)
  );
  await Promise.all(promises);
}

// 获取区域名称
function getAreaName(node) {
  if (node.id === 1) {
    return companyStore.currentCompany.location;
  } else if (node.$$data.isVirtualNode) {
    return ''; // 虚拟节点不显示区域
  } else {
    return node.$$data.supply_region || '-'
  }
}

// 判断区域名称是否被截断
function isAreaNameTruncated(node) {
  const areaName = getAreaName(node);
  return areaName && areaName.length > 10;
}


// 监听 meterList 变化，自动刷新读数
watch(
  () => props.meterList,
  async (newVal, oldVal) => {
    await refreshLatestReadings();
  }
);

// 节点图标
const getNodeIconClass = (node) => {
  if (node.id === 1) {
    return "fa-building company-icon";
  } else if (node.$$data.isVirtualNode) {
    return "fa-folder-o folder-icon"; // 为虚拟分组节点使用文件夹图标
  } else {
    return "fa-tachometer meter-icon";
  }
};
</script>

<style lang="scss" scoped>
.meter-tree-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: var(--el-bg-color);

  .control-panel {
    margin-top: 1rem;
    background-color: var(--el-bg-color-overlay);

    .control-item {
      display: flex;
      align-items: center;
      gap: 8px;

      .control-label {
        font-size: 14px;
        color: var(--el-text-color-regular);
        display: flex;
        align-items: baseline;
        gap: 4px;

        .fa {
          font-size: 14px;
        }
      }
    }
  }

  .tree-container {
    flex: 1;
    overflow: auto;
  }
}

.custom-tree-org {
  :deep(.tree-org-node) {
    .tree-org-node__inner {
      background: var(--el-bg-color-overlay);
      border: 1px solid var(--el-border-color);
      border-radius: var(--el-border-radius-base);
      box-shadow: var(--el-box-shadow-light);
      transition: all 0.3s ease;

      &:hover {
        box-shadow: var(--el-box-shadow);
        border-color: var(--el-color-primary-light-3);
      }
    }

    .tree-org-node__text {
      padding: 0;

      .node-content {
        padding: 12px 16px;

        .node-header {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 8px;

          &.is-center {
            justify-content: center;
            margin-bottom: 0; // 移除底部边距，因为虚拟节点没有node-info

            .node-title {
              flex: 0 auto; // 不要占满所有空间
              font-weight: 500; // 稍微减轻字体粗细
              color: var(--el-text-color-secondary); // 使用次要文本颜色
            }
          }


          .fa {
            font-size: 18px;

            &.company-icon {
              color: var(--el-color-warning);
            }

            &.meter-icon {
              color: var(--el-color-primary);
            }

            &.folder-icon {
              color: var(--el-color-info); // 使用灰色表示文件夹
            }
          }

          .node-title {
            font-weight: 600;
            color: var(--el-text-color-primary);
            font-size: 14px;
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }

        .node-info {
          display: flex;
          align-items: center;
          justify-content: space-between;
          gap: 8px;

          .node-area {
            display: flex;
            align-items: center;
            gap: 4px;
            font-size: 12px;
            color: var(--el-text-color-secondary);
            max-width: 150px;

            .fa {
              font-size: 14px;
              flex-shrink: 0;
            }

            .area-text {
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }

          .node-reading {
            font-size: 12px;
            padding: 2px 6px;
            border-radius: var(--el-border-radius-small);
            background-color: var(--el-color-primary-light-9);
            color: var(--el-color-primary);
          }
        }
      }
    }
  }
}
</style>